package com.fisher.checker;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class SharedPublicKey {
    private static String read(Context context) {
        StringBuilder publicKeyBuilder = new StringBuilder();

        try (InputStream inputStream = context.getResources().openRawResource(R.raw.public_key);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {

            String line;
            while ((line = reader.readLine()) != null) {
                publicKeyBuilder.append(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        return publicKeyBuilder.toString();
    }


    public static String savePublicKeyToPreferences(Context context) {
        String publicKey = read(context);
        AppPreferences.saveSharedPublicKey(context, publicKey);
        return publicKey;
    }

    public static String loadPublicKey(Context context) {
        String sharedPublicKey = AppPreferences.getSharedPublicKey(context);
        if(sharedPublicKey == null){
            sharedPublicKey = savePublicKeyToPreferences(context);
        }
        return sharedPublicKey;
    }


}
